import "@/lib/audio.js"
import "@/lib/socket.io.js"

import { getToken as getCookieToken } from "@/utils/cache/cookies"
import { SingletonFactory } from "./single"

declare global {
  interface Window {
    /** SpeechSDK */
    SpeechSDK: Record<string, any>
    /** io */
    io: Record<string, any>
  }
}

type Event =
  | "start"
  | "creating"
  | "close"
  | "chat_audio"
  | "chat_text"
  | "chat_text_end"
  | "chat_audio_end"
  | "aipic_done"
  | "aipic_progress"
  | "login"
  | "tts"
  | "image"
  | "image_progress"
  | "chat"
// type SocketType = 'aiweb' | 'aipic' | "aiengine"
// const mode = import.meta.env.PROD  ? '' : '/chat_msg'
const fetchUrl = "https://robot.lnkyeah.com"
// const testToken =
//   "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJyb2JvdCIsImF1ZCI6ImZvbnQiLCJpYXQiOjE3MDYwMzcyMjcsImV4cCI6MTcwODcxNTYyNywidWlkIjoyfQ.3cKmSaEoM9fPE0Yprd4vOjScgxKRM6cgSyuNmDFcBHo"

export default class Speech extends SingletonFactory<Speech>() {
  creating = false
  private $on = new Map<Event, Array<Function>>()
  private authorizationToken: any
  private socket: any = null
  private recognizer: any
  private getAuthorizationToken() {
    // const authorizationEndpoint = "/index/index/speek";
    const authorizationEndpoint = `${fetchUrl}/index/index/speek`
    if (authorizationEndpoint) {
      const a = new XMLHttpRequest()
      a.open("GET", authorizationEndpoint)
      a.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
      a.send("")
      a.onload = (res: any) => {
        const token = JSON.parse(atob(res.target.responseText.split(".")[1]))
        const regionOptions = token.region
        console.log("建立语音链接成功", regionOptions)
        this.authorizationToken = res.target.responseText
      }
    }
  }
  async login() {
    const response = await fetch(`${fetchUrl}/index/socket_login`, {
      method: "POST",
      headers: {
        Authorization: getCookieToken() as any
      }
    })
    const res = (await response.json()) as any
    if (res.data?.socket_token) {
      this.socket.emit("login", { token: res.data?.socket_token })
    }
  }
  init() {
    // const aiWebSocketUrl = 'https://aiweb.lnkyeah.com'
    // const aiPicSocketUrl = 'https://aipic.lnkyeah.com'
    const robotSocketUrl = "https://engine-robot.lnkyeah.com"
    // const url = socketType === 'aiweb' ? aiWebSocketUrl : socketType === 'aipic' ? aiPicSocketUrl : engineRobotSocketUrl
    this.socket = window.io.connect(robotSocketUrl, {
      // query: {
      //   token: getCookieToken(),
      //   // token: "d4c3550d8bc1c52ad0a41d1a498980cb",
      //   timestamp: "1704427081"
      // },
      // reconnection: true, // 开启自动重连
      // reconnectionAttempts: Infinity, // 无限重连尝试
      // reconnectionDelay: 1000, // 初始重连延迟毫秒数
      // reconnectionDelayMax: 5000, // 最大重连延迟毫秒数
      // randomizationFactor: 0.5
    })

    this.socket.on("login_status", (msg: any) => {
      console.log("login_status", msg)
    })

    this.socket.on("chat_text", (msg: any) => {
      this.emit("chat_text", msg)
    })

    this.socket.on("chat_audio", (msg: any) => {
      this.emit("chat_audio", msg)
    })

    this.socket.on("chat_text_end", (msg: any) => {
      this.emit("chat_text_end", msg)
    })

    this.socket.on("chat_audio_end", (msg: any) => {
      this.emit("chat_audio_end", msg)
    })

    // this.socket.on("aipic_done", (msg: any) => {
    //   this.emit("aipic_done", msg)
    // });

    // this.socket.on("aipic_progress", (msg: any) => {
    //   this.emit("aipic_progress", msg)
    // });

    // 接收文本 on_login登录成功
    this.socket.on("login", (msg: any) => {
      this.login()
      console.log("登陆成功", msg)
    })

    // 接收语音
    this.socket.on("tts", (msg: any) => {
      this.emit("tts", msg)
    })

    // 接收图片
    this.socket.on("image", (msg: any) => {
      this.emit("image", msg)
    })

    // 接收图片加载进度
    this.socket.on("image_progress", (msg: any) => {
      this.emit("image_progress", msg)
    })

    //这个是接收聊天信息的
    this.socket.on("chat", (msg: any) => {
      this.emit("chat", msg)
    })

    // this.getAuthorizationToken();
  }

  // 关闭socket
  close() {
    this.socket?.close()
  }

  async getMsg(message: string, robot_id: number | string = 2) {
    const response = await fetch(`${fetchUrl}/api/index/get_robot_ws`, {
      method: "POST",
      mode: "cors",
      headers: {
        "Content-Type": "application/json"
        // token: "88476704-0064-4422-942f-7fd243cd5c7d"
      },
      body: JSON.stringify({
        robot_id,
        message
      })
    })
    const res = (await response.json()) as any
    const data = res.data
    this.socket.emit("do_chat", {
      messages_id: data.messages_id,
      messages: message,
      timestamp: data.timestamp,
      sing: data.sing,
      is_memory: "Y", //记忆体
      is_audio: "N", //是否语音
      room_id: data.room_id,
      robot_id: data.robot_id,
      back_url: data.back_url,
      voice_name: "alloy",
      model_name: "Yunshan-v1"
    })
    return data
  }
  async getDoPic(message: string) {
    const response = await fetch(`${fetchUrl}/index/index/do_pic`, {
      method: "GET",
      mode: "cors",
      headers: {
        "Content-Type": "application/json"
      }
    })
    const data = (await response.json()) as any
    this.socket.emit("do_image", {
      messages_id: data.messages_id,
      message,
      timestamp: data.timestamp,
      sing: data.sing,
      back_url: data.back_url
    })
    return data
  }
  // tts
  async getTts(p: any) {
    const response = await fetch(`${fetchUrl}/index/index/tts_speak`, {
      method: "GET",
      mode: "cors",
      headers: {
        "Content-Type": "application/json"
      }
    })
    const data = (await response.json()) as any
    console.log(data, p, "tts")
    this.socket.emit("do_speak", {
      messages_id: data.messages_id,
      messages: p.messages,
      timestamp: data.timestamp,
      sing: data.sing,
      // voice_name:p.voice_name,
      voice_name: "alloy"
    })
    return data
  }
  off(event: Event) {
    if (this.$on.has(event)) {
      this.$on.delete(event)
    }
  }
  on(event: Event, callback: Function) {
    if (this.$on.has(event)) {
      const callbacks = this.$on.get(event) as Array<Function>
      callbacks.push(callback)
      this.$on.set(event, callbacks)
    } else {
      this.$on.set(event, [callback])
    }
  }
  emit(event: Event, value?: any) {
    const eventQueue = this.$on.get(event)
    if (eventQueue?.length) {
      for (let i = 0; i < eventQueue.length; i++) {
        eventQueue[i](value)
      }
    }
  }
  start() {
    this.emit("start")
    // 使用默认的麦克风输入
    const audioConfig = window.SpeechSDK.AudioConfig.fromDefaultMicrophoneInput()
    // 创建语音配置
    const speechConfig = window.SpeechSDK.SpeechConfig.fromAuthorizationToken(this.authorizationToken, "eastus")
    speechConfig.speechRecognitionLanguage = "zh-CN"
    // 创建语音识别器
    this.recognizer = new window.SpeechSDK.SpeechRecognizer(speechConfig, audioConfig)
    console.log("调起了麦克风", this.recognizer)
    // 开始识别
    this.recognizer.recognizeOnceAsync(
      async (result: any) => {
        const recognizedText = result.text
        console.log("返回语音解析", recognizedText)
        await this.recognizer.close()
        this.emit("close", recognizedText)
      },
      (error: any) => {
        console.log("麦克风启动失败，发送错误", error)
        this.recognizer.close()
      }
    )
  }
  // close() {
  //   if (this.recognizer) {
  //     // this.recognizer.stopContinuousRecognitionAsync(res => {
  //     //   console.log("stop", res);
  //     // });
  //     this.recognizer.close();
  //   }
  // }
}
